<template>
  <div class="container mt-5">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="300px"
      label-position="top"
    >
      <el-form-item label="表名" prop="tableName">
        <el-input v-model="form.tableName" placeholder="请输入表名"></el-input>
      </el-form-item>
      <el-form-item label="表说明" prop="tableComment">
        <el-input
          v-model="form.tableComment"
          placeholder="请输入表说明"
        ></el-input>
      </el-form-item>

      <el-form-item label="字段列表">
        <div class="table-actions mb-2">
          <el-button
            class="add-column-btn"
            type="primary"
            @click="addColumn"
            size="small"
            >添加字段</el-button
          >
        </div>
        <el-table :data="form.fields" border style="width: 100%">
          <el-table-column prop="fieldName" label="字段名" align="center">
            <template #default="{ row }">
              <div class="table-container">
                <span class="spanSign">*</span
                ><el-input v-model="row.fieldName" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="fieldType" label="类型" align="center">
            <template #default="{ row }">
              <el-select v-model="row.fieldType" style="width: 100%">
                <el-option value="INT">INT</el-option>
                <el-option value="BIGINT">BIGINT</el-option>
                <el-option value="tinyint">tinyint</el-option>
                <el-option value="VARCHAR">VARCHAR</el-option>
                <el-option value="TEXT">TEXT</el-option>
                <el-option value="DATETIME">DATETIME</el-option>
                <el-option value="DOUBLE">DOUBLE</el-option>
                <el-option value="DECIMAL">DECIMAL</el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="fieldLength" label="长度" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.fieldLength" :min="0" />
            </template>
          </el-table-column>
          <el-table-column label="属性" align="center">
            <template #default="{ row }">
              <div style="display: flex; flex-direction: column; gap: 8px">
                <el-checkbox v-model="row.isKey">主键</el-checkbox>
                <el-checkbox v-model="row.isAddId">自增</el-checkbox>
                <el-checkbox v-model="row.isNull">允许NULL</el-checkbox>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="fieldComment" label="注释" align="center">
            <template #default="{ row }">
              <div class="table-container">
                <span class="spanSign">*</span
                ><el-input v-model="row.fieldComment" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template #default="{ $index }">
              <el-button
                type="danger"
                size="small"
                @click="removeColumn($index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">创建表</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button @click="goToList">查看列表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import { ref } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";

const form = ref({
  tableName: "",
  tableComment: "",
  fields: [
    {
      fieldName: "",
      fieldType: "VARCHAR",
      fieldLength: 50,
      isKey: false,
      isAddId: false,
      isNull: false,
      fieldComment: "",
    },
  ],
});

const rules = {
  tableName: [{ required: true, message: "请输入表名", trigger: "blur" }],
  tableComment: [{ required: true, message: "请输入表说明", trigger: "blur" }],
};

// 表单引用
const formRef = ref();

// 添加字段
const addColumn = () => {
  if (form.value.fields.length === 0 || validateLastRow()) {
    form.value.fields.push({
      fieldName: "",
      fieldType: "VARCHAR",
      fieldLength: 50,
      isKey: false,
      isAddId: false,
      isNull: false,
      fieldComment: "",
    });
  } else {
    ElMessage.error("请先完成上一行");
  }
};

// 删除字段
const removeColumn = (index) => {
  form.value.fields.splice(index, 1);
};

// 校验表格字段
const validateFields = () => {
  const fields = form.value.fields;
  for (let i = 0; i < fields.length; i++) {
    const field = fields[i];
    if (!field.fieldName.trim()) {
      ElMessage.error(`第 ${i + 1} 行字段名不能为空`);
      return false;
    }
    if (!field.fieldType) {
      ElMessage.error(`第 ${i + 1} 行字段类型不能为空`);
      return false;
    }
    if (!field.fieldComment.trim()) {
      ElMessage.error(`第 ${i + 1} 行注释不能为空`);
      return false;
    }
  }
  return true;
};

// 提交表单
const submitForm = async () => {
  try {
    // 主表单字段校验
    await formRef.value.validate();
  } catch {
    ElMessage.error("请填写完整的基本信息");
    return;
  }

  // 表格字段校验
  if (!validateFields()) return;

  try {
    const processedColumns = form.value.fields.map((col) => ({
      ...col,
      isKey: col.isKey ? 1 : 0,
      isAddId: col.isAddId ? 1 : 0,
      isNull: col.isNull ? 1 : 0,
    }));

    const response = await axios.post(
      "http://localhost:8080/api/dbtable/create",
      {
        tableName: form.value.tableName,
        tableComment: form.value.tableComment,
        fields: processedColumns,
      }
    );

    console.log(response.data);
    if(response.data.code === 200){
      ElMessage.success("表创建成功");
    }else if(response.data.code === 1001){
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error("创建失败: " + error.message);
  }
};

// 重置表单
const resetForm = () => {
  form.value = {
    tableName: "",
    tableComment: "",
    fields: [
      {
        fieldName: "",
        fieldType: "VARCHAR",
        fieldLength: 50,
        isKey: false,
        isAddId: false,
        isNull: false,
        fieldComment: "",
      },
    ],
  };
};

// 跳转到列表页
const goToList = () => {
  router.push("/dbList");
};

const validateLastRow = () => {
  const fields = form.value.fields;
  const lastField = fields[fields.length - 1];

  if (
    !lastField.fieldName.trim() ||
    !lastField.fieldType ||
    !lastField.fieldComment.trim()
  ) {
    return false;
  }

  return true;
};
</script>
<style scoped lang="scss">
.container {
  margin: 20px 50px;
}
.table-actions {
  display: flex;
  justify-content: flex-end;
  .add-column-btn {
    margin-bottom: 20px;
  }
}
.table-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.spanSign {
  margin-right: 10px;
  color: red;
}
</style>
